//
//  PywCheckSmsCodeApi.m
//  PywSdk
//
//  Created by smallwave on 16/8/3.
//  Copyright © 2016年 zero. All rights reserved.
//

#import "PywCheckSmsCodeApi.h"
#import "AIFCheckSmsCodeManager.h"
#import "PywMBProgressHUD+Pyw.h"
#import "PropertyListReformer.h"

@interface PywCheckSmsCodeApi ()<ETAPIManagerCallBackDelegate>

@end

@implementation PywCheckSmsCodeApi

- (void)requestCheckSmsCodeWithParams:(MutableDictionary *)params
                              success:(Successd)success
                                 fail:(Failure)fail{
    self.successd = success;
    self.failure = fail;
    
    AIFCheckSmsCodeManager *manager = [[AIFCheckSmsCodeManager alloc] init];
    manager.delegate = self;
    manager.phoneNum = [params objectForKey:@"phone"];
    manager.smsCode = [params objectForKey:@"smscode"];
    manager.smsType = [params objectForKey:@"smstype"];
    [manager loadData];
}
#pragma mark - ETAPIManagerCallBackDelegate
- (void)managerCallAPIDidSuccess:(ETApiBaseManager *)manager{
    PropertyListReformer *reformer = [[PropertyListReformer alloc] init];
    NSDictionary *dict = [manager fetchDataWithReformer:reformer];
    [PywMBProgressHUD hideHUDForView:[UIApplication sharedApplication].keyWindow animated:NO];
    
    [self checkSmsCodeWithDict:dict];
}

- (void)managerCallApiDidFailed:(ETApiBaseManager *)manager{
    [PywMBProgressHUD hideHUDForView:[UIApplication sharedApplication].keyWindow animated:NO];
    [PywMBProgressHUD showError:@"似乎已断开与互联网的连接?" toView:[UIApplication sharedApplication].keyWindow];
    
    if (self.failure) {
        self.failure([self errorWithCode:0]);
    }
}

/**
 *  校验验证码
 *
 *  @param dict <#dict description#>
 */
- (void)checkSmsCodeWithDict:(NSDictionary *)dict{
    int resultCode = [[dict objectForKey:@"ack"] intValue];
    NSString *errorMsg = [NSString stringWithFormat:@"%@",dict[@"msg"]];
    if (resultCode == 200) {
        
        // 保存返回数据
        NSString *account_num = [NSString stringWithFormat:@"%@",dict[@"data"][@"account_num"]];
        NSString *is_check_smscode = [NSString stringWithFormat:@"%@",dict[@"data"][@"is_check_smscode"]];
        NSDictionary *data = @{@"account_num":account_num,
                               @"is_check_smscode":is_check_smscode};
        
        if (self.successd) {
            self.successd(nil,data);
        }
    } else {
        
        [PywMBProgressHUD showError:errorMsg toView:[UIApplication sharedApplication].keyWindow];
        if (self.failure) {
            self.failure([self errorWithCode:resultCode]);
        }
    }
}

@end
